<?php
    namespace app\minprogram\model;
    use app\common\model\Model;
    use think\Db;
    
//  model 类
    class LoginModel extends Model
    {
        const TABLE_NAME = 'user';
        const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_4;

        protected $name = self::TABLE_NAME;

        //使用 微信小程序 openid储存新用户
        //通过 手机 作为 唯一判断条件
        public static function saveNewUser($phone,$openid,$user_name){
            $info = self::getUserByPhone($phone);
            if(empty($info)){

                $data =['user_phone' => $phone, 'wx_min_openid' => $openid];
                if(empty($user_name))
                {
                    $data['user_name']='hz_'.substr($phone,8);
                }else{
                    $data['user_name']=$user_name;
                }
                return self::commonQuery(self::TABLE_NAME)->insert($data,false,true);
            }else{
                if(empty($info['wx_min_openid']))
                {
                    self::commonQuery(self::TABLE_NAME)->where(['user_id'=>$info['user_id']])
                          ->setField('wx_min_openid',$openid);

                }else if($info['wx_min_openid'] != $openid){
                    return false;
                }
                return $info['user_id'];
            }

        }
        //微信小程序 openid 获取 用户信息
       public static function getUserInfoByWxOpenid($wx_openid)
       {
           $info =  self::commonQuery(self::TABLE_NAME)->where(['wx_min_openid'=>$wx_openid])->find();
           if(empty($info) || $info['is_del']==1)
           {
               return [];
           }
           return $info;

       }


        //用户登录
        public static function  getUserByPhone($phone)
        {
            return  self::commonQuery(self::TABLE_NAME)
                ->where(['user_phone'=>$phone,'is_del'=>0])
                ->find();

        }
        public static function handleLoginUserInfo($info)
        {
            return ['user_id'=>$info['user_id'],
                'user_name'=>$info['user_name'],
                'user_avatar'=>$info['user_avatar'],
                'user_type'=>$info['user_type']
            ];
        }
        public static function updateUserPassword($user_id,$password)
        {
            return self::commonQuery(self::TABLE_NAME)
                   ->where(['user_id'=>$user_id])
                   ->setField('user_passwd',$password);
        }
    }


    